package com.ruoyi.system.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtils {
//    TODO ：生成拼音标识的方法太垃圾了，需要改进
    private String toPinyinSlug(String input) {
        if (input == null) {
            return "";
        }
        input = input.trim();
        if (input.isEmpty()) {
            return "";
        }
        HanyuPinyinOutputFormat fmt = new HanyuPinyinOutputFormat();
        fmt.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        fmt.setVCharType(HanyuPinyinVCharType.WITH_V);
        fmt.setCaseType(HanyuPinyinCaseType.LOWERCASE);

        StringBuilder sb = new StringBuilder();
        for (char ch : input.toCharArray()) {
            // 判断中文字符范围
            if (Character.toString(ch).matches("[\\u4E00-\\u9FFF]")) {
                try {
                    String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(ch, fmt);
                    if (pinyins != null && pinyins.length > 0) {
                        sb.append(pinyins[0]);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    // 忽略该字符的拼音
                }
            } else {
                if (Character.isLetterOrDigit(ch)) {
                    sb.append(Character.toLowerCase(ch));
                } else if (Character.isWhitespace(ch) || ch == '-' || ch == '_') {
                    sb.append('-');
                } // 其它符号忽略
            }
        }
        String slug = sb.toString().replaceAll("-{2,}", "-");
        // 去除首尾 '-'
        slug = slug.replaceAll("^-|-$", "");
        // 截断，避免过长
        int max = 100;
        if (slug.length() > max) {
            slug = slug.substring(0, max);
        }
        return slug;
    }

}
